﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataSet1TableAdapters;
using System.Data;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Globalization;
using ByteBlocks.FaceBookWeb;

public partial class DefaultZoom: System.Web.UI.Page
{
        DisplayTableAdapter DisplayTa = new DisplayTableAdapter();
        DataSet1.DisplayDataTable DispeyDa = new DataSet1.DisplayDataTable();
        RakstiTableAdapter RakstiTa = new RakstiTableAdapter();
        DataSet1.RakstiDataTable RakstiDa = new DataSet1.RakstiDataTable();

        string[] XMLfaili = { "Komentari_XML\\RakstuComenti.xml",
                                "Komentari_XML\\FotoKomentari.xml",
                                "Komentari_XML\\LVvideo.xml",
                                "Komentari_XML\\BikeCheckKomentari.xml",
                            "t","t","T","T","T","t","t","T","T","T","T","T",
                            "Komentari_XML\\InternationalVideo.xml"};
    
    // Video ir ID 17 "t","t","T","T","T","T","T",
       // šāda secība ir debagojot Kompī, un augšā ir priekš Servera! 
    /*    string[] XMLfaili = {    "Komentari_XML\\RakstuComenti.xml",
                                "Komentari_XML\\FotoKomentari.xml",
                                "Komentari_XML\\LVvideo.xml",
                                "Komentari_XML\\BikeCheckKomentari.xml",
                            "t","t","T","T","T",
                            "Komentari_XML\\InternationalVideo.xml"}; // Video ir ID 17 
    */
//   domāts priekš Shopa datubāzes
        string[] KomentarTxt = new string[0];
        string[] KomentarAutors = new string[0];
        string[] KomentarDatums = new string[0];
        int SadalasIDx = 0;
        int RakstaID = 0;
            int rakstaID_nr = 0;
        int RowNr = 0;


    protected void Page_Load(object sender, EventArgs e)
    {
        string Title = "PARBMX  |  ";
      //  int rakstaID_nr = Convert.ToInt16(String.Format(Request.QueryString["value"]));

        string html_txt = String.Format(Request.QueryString["value"]);
        string Virsraksts = "";
        bool Svitra = false;
        int stringNR = 0;
        if (html_txt.Contains("--") == true)
        {
            stringNR = html_txt.LastIndexOf("--");
            Virsraksts = html_txt.Substring(0, stringNR);
            Virsraksts += html_txt.Substring(stringNR+2);
            html_txt = Virsraksts;
            Virsraksts = "";
            Svitra = true;
        }

        if (html_txt.Contains("-") == true)
        {
            string[] Tsplit = html_txt.Split('-');

            for (int f = 0; f < Tsplit.Length; f++)
            {
                if (f == Tsplit.Length - 1)
                {
                    Virsraksts += Tsplit[f]; // Beigas Stringam ta neliek " " Space
                }
                else
                {
                    Virsraksts += Tsplit[f] + " ";
                }
            }
        }
        else
        { // Ja teksts ir prasts vārds BEZ (-) vai (--)
            Virsraksts = html_txt;
        }

        if (Svitra == true)
        {
            string Vs = "";
            Vs = Virsraksts.Substring(0, stringNR)+"-"+Virsraksts.Substring(stringNR);
            Virsraksts = Vs;
        }

        rakstaID_nr = 0;
        RakstiDa = RakstiTa.GetData();
        RowNr = 0;
        foreach (DataSet1.RakstiRow Srow in RakstiDa)
        {
            if (Srow.Virsraksts == Virsraksts)
            {
                rakstaID_nr = Srow.ID_name;
                break;
            }
            RowNr++;
        }
        HtmlMeta theMetaTag = new HtmlMeta();
        theMetaTag.Attributes.Add("name", "description");

        DateTime datums = RakstiDa[RowNr].datums;
        string datumsSt = datums.Date.ToShortDateString();
        string virsaraksts = RakstiDa[RowNr].Virsraksts;
        string bilde = " ";
        string bildebig = " ";
        string bildeThumb = " ";
        try
        {
            bildeThumb = RakstiDa[RowNr].bildeTumb;
            bilde = RakstiDa[RowNr].bilde; // bildeTumb;
            bildebig = RakstiDa[RowNr].bilde;
        }
        catch (NullReferenceException) { }
        catch (IndexOutOfRangeException) { }
        catch (StrongTypingException) { }

        string raksts = RakstiDa[RowNr].raksts;
        raksts = raksts.Replace("id='bild'", "data-lightbox='roadtrip'");       
        string autors = RakstiDa[RowNr].autors;
        string sadalulists = "";
        try { sadalulists = RakstiDa[RowNr].SadaluLists; }
        catch (StrongTypingException caste)
        { sadalulists = " "; }

        Title += sadalulists + " : " + virsaraksts;
        Page.Title = Title;
        Dzinejs Dz = new Dzinejs();


        //theMetaTag.Attributes.Add("content", autors +" : "+ Dz.MakeShortText(raksts,100)); // Dz.MakeShortTagFreeText(raksts, 100));
        //Page.Header.Controls.Add(theMetaTag);
       
        // https://developers.facebook.com/tools/lint   tipa Facebook Test lapa un trūkst šito Tagu.
        // info http://developers.facebook.com/docs/opengraph/  Open Graph Protocol
//        Required Property Missing	og:title is required
//Required Property Missing	og:type is required
//Required Property Missing	og:url is required
//Required Property Missing	og:image is required        
        FBLikeButton.Url = "http://www.parbmx.com/DefaultZoom.aspx?value=" + HttpUtility.UrlEncode(Virsraksts);
        FBLikeButton.ShowFaces = true;

        MasterPage myMaster = (MasterPage)this.Master;
        myMaster.MetaDescription = Dz.MakeShortText(raksts, 100);
        myMaster.MetaPageURL = FBLikeButton.Url;
        if (bildeThumb.Contains("http"))
        {
            myMaster.MetaPageImage = bildeThumb;
        }
        else
        {
            myMaster.MetaPageImage = "http://www.parbmx.com/" + bildeThumb;
        }

        myMaster.MetaPageTitle = virsaraksts;

        //string[] MetaContent = { virsaraksts, "article", FBLikeButton.Url, bilde, "PARBMX",
        //                           "USER_ID,USER_ID2", Dz.MakeShortText(raksts, 100)};
        //string[] MetaProperty = { "content", "og:type", "og:url", "og:image", "og:site_name", "fb:admins", "og:description", };

        //AddMetaTags(MetaContent, MetaProperty, Page.Header.Controls);
            

        //theMetaTag.Attributes.Add("og:type", "article");

        //theMetaTag.Attributes.Add("og:url", FBLikeButton.Url );
        //theMetaTag.Attributes.Add("og:image", bilde);
        //theMetaTag.Attributes.Add("og:site_name", "PARBMX");
        //theMetaTag.Attributes.Add("fb:admins", "USER_ID,USER_ID2"); // Vaig Jaņa un citu Facebook USER ID
        //theMetaTag.Attributes.Add("og:description",Dz.MakeShortText(raksts,100));
        //Page.Header.Controls.Add(theMetaTag);

        HttpContext.Current.Session["dat"] = datumsSt;
        HttpContext.Current.Session["vraksts"] = virsaraksts;
        HttpContext.Current.Session["bilde"] = bilde;
        HttpContext.Current.Session["bildebig"] = bildebig;
        HttpContext.Current.Session["raksts"] = raksts;
        HttpContext.Current.Session["autors"] = autors;
        HttpContext.Current.Session["slists"] = sadalulists;



        
        //e.Item.Controls.Add(FBlike);

        if ((bilde != "")&(bildebig != "")) // ja abas bildēs ir links ta rāda ja kaut vienā nav ta nerāda.
        {
            HyperLink1.NavigateUrl = bildebig;
            HyperLink1.ImageUrl = bilde;
        }
        // Komentāru pievienošanas Kods:
        DispeyDa = DisplayTa.GetDataByRakstID(rakstaID_nr);
        SadalasIDx = DispeyDa[0].SadalasID - 1;
        RakstaID = RakstiDa[RowNr].ID_name;
        string virtualPathDir = Server.MapPath("~/");
        // Ielādē pareizo XML failu (katrai Sadaļai savs XML fails kas atrodās XMLfaili[] string arrayā.

        /* komentāri ir sačakarēti*/
        XmlTextReader Sadalla = new XmlTextReader(virtualPathDir + XMLfaili[DispeyDa[0].SadalasID-1]);
        XmlDocument Comment = new XmlDocument();
        Comment.Load(Sadalla);
        Sadalla.Close();
        XmlNode RakstuKomentari = Comment.ChildNodes[2];
      //  int RakstuKom_Count = RakstuKomentari.ChildNodes.Count;
        foreach (XmlNode xmlRaksts in RakstuKomentari.ChildNodes)
        {
            if ((Convert.ToInt32(xmlRaksts.Attributes["ID"].Value)) == rakstaID_nr)
            {
                if (xmlRaksts.ChildNodes.Count > 0)
                {// Ja ir kaut 1 komentārs tad nolasa komentārus: 
                    int Koment_count = xmlRaksts.ChildNodes.Count;
                    Array.Resize(ref KomentarAutors, Koment_count);
                    Array.Resize(ref KomentarTxt, Koment_count);
                    Array.Resize(ref KomentarDatums, Koment_count);
                    int Ci = 0;
                    foreach (XmlNode komentars in xmlRaksts)
                    {
                        KomentarDatums[Ci] = komentars.ChildNodes[0].InnerText;
                        KomentarAutors[Ci] = komentars.ChildNodes[1].InnerText;
                        KomentarTxt[Ci] = komentars.ChildNodes[2].InnerText;
                        Ci++;
                    }
                    break;
                }
            }
        }
        
        Repeater1.DataSource = KomentarAutors;
        Repeater1.DataBind();

        DataTable DataTableNEW = new DataTable();
        CreateDataTableVideo(DataTableNEW, "http://shop.parbmx.com/XmlAkcijaNEW.xml", true);

        PagedDataSource objPds = new PagedDataSource(); // MAKE PAGING
        objPds.DataSource = DataTableNEW.DefaultView;
        objPds.AllowPaging = true;
        objPds.PageSize = 6;
        objPds.CurrentPageIndex = 0;// -1;
        Repeater3.DataSource = objPds;
        Repeater3.DataBind();

    }
    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ^ e.Item.ItemType == ListItemType.AlternatingItem)
        {
            int Nr = e.Item.ItemIndex;
            Label Tl = ((Label)e.Item.FindControl("Label1"));
            Tl.Text = KomentarAutors[Nr];
            Label T2 = ((Label)e.Item.FindControl("Label2"));
            T2.Text = KomentarTxt[Nr];
            Label T3 = ((Label)e.Item.FindControl("Label3"));
            T3.Text = KomentarDatums[Nr];
            if (User.Identity.IsAuthenticated == true)
            {
                //if (User.Identity.Name == "EpisLog") // TIkai Loginam kas ir Lv lapām. Lietuviešu Login ir Cits: "LTparBMXpage"
                //{
                    LinkButton Del = ((LinkButton)e.Item.FindControl("LinkButton1"));
                    Del.Enabled = true;
                    Del.Text = "Delet";
                //}
            }
            Label T4 = ((Label)e.Item.FindControl("Label4"));
            T4.Text = "</tr><tr>";
        }
    }

    protected void Button_KomentAdd_Click(object sender, EventArgs e)
    {
        // kods kas atrod Komentētāja IP adresi! 
        bool Attack = false;
        string HackFilter = TextBox__komentari.Text;
        if (HackFilter.Contains("http://"))
        {
            Attack = true;
            Label8.Text = "Don't use http:// in coments";
            Label8.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            if (HackFilter.Contains("HTTP://"))
            {
                Attack = true;
                Label8.Text = "Don't use http:// in coments";
                Label8.ForeColor = System.Drawing.Color.Red;
            }
        }

        if(Attack == false)
        {
            string ip;
            ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(ip))
            {
                string[] ipRange = ip.Split(',');
                int le = ipRange.Length - 1;
                string trueIP = ipRange[le];
            }
            else
            {
                ip = Request.ServerVariables["REMOTE_ADDR"];
            }
            // kautkādu IP es dabūnu.
            ip = " @ " + ip;
            // IP blocker filter. 
            bool IpNotBlocked = true;
            string[] IPs = { "188.112.137.95" };
            foreach (string Ipss in IPs)
            {
                if (Ipss == ip)
                {
                    IpNotBlocked = false;
                }
            }
            if (IpNotBlocked)
            {

                if (TextBox_Koment_Vards.Text.Length > 0)
                {
                    string virtualPathDir = Server.MapPath("~/");
                    XmlTextReader Sadalla = new XmlTextReader(virtualPathDir + XMLfaili[SadalasIDx]);
                    XmlDocument Comment = new XmlDocument();
                    Comment.Load(Sadalla);
                    Sadalla.Close();
                    XmlNode RakstuKomentari = Comment.ChildNodes[2];
                    bool jauIR_komentari = false;
                    foreach (XmlNode Kom in RakstuKomentari)
                    {
                        string Nr_A = Kom.Attributes["ID"].Value;
                        if (Convert.ToInt32(Nr_A) == RakstaID)
                        {
                            // ievieto jauno Komentāru
                            XmlNode newNode = Comment.CreateNode(XmlNodeType.Element, "komentars", "");
                            XmlNode NodeKoment = Comment.CreateNode(XmlNodeType.Element, "datums", "");
                            string Datums = System.DateTime.Now.ToString("f", CultureInfo.InvariantCulture);
                            NodeKoment.InnerXml = Datums;
                            newNode.AppendChild(NodeKoment);
                            XmlNode NodeKoment2 = Comment.CreateNode(XmlNodeType.Element, "vards", "");
                            xmlAdd_text(NodeKoment2, TextBox_Koment_Vards.Text + ip);
                            newNode.AppendChild(NodeKoment2);
                            XmlNode NodeKoment3 = Comment.CreateNode(XmlNodeType.Element, "text", "");
                            xmlAdd_text(NodeKoment3, TextBox__komentari.Text);
                            newNode.AppendChild(NodeKoment3);
                            Kom.InsertAfter(newNode, Kom.ChildNodes[Kom.ChildNodes.Count - 1]);
                            jauIR_komentari = true;
                            break;
                        }
                    }

                    if (jauIR_komentari == false)
                    {
                        // veido <Raksts ID="x">
                        XmlNode RakstsNode = Comment.CreateNode(XmlNodeType.Element, "Raksts", "");
                        XmlAttribute IDatribute = Comment.CreateAttribute("ID");
                        IDatribute.Value = RakstaID.ToString();
                        RakstsNode.Attributes.Append(IDatribute);
                        // veido <Komentars>
                        XmlNode newNode = Comment.CreateNode(XmlNodeType.Element, "komentars", ""); // NEW node ko Pielikšu klāt sarakstam
                        // veido <datums>
                        XmlNode NodeKoment = Comment.CreateNode(XmlNodeType.Element, "datums", "");
                        string Datums2 = System.DateTime.Now.ToString("f", CultureInfo.InvariantCulture);
                        NodeKoment.InnerXml = Datums2;
                        newNode.AppendChild(NodeKoment);
                        //veido <Vards>
                        XmlNode NodeKoment2 = Comment.CreateNode(XmlNodeType.Element, "vards", "");
                        xmlAdd_text(NodeKoment2, TextBox_Koment_Vards.Text + ip);
                        newNode.AppendChild(NodeKoment2);
                        // veido <text>
                        XmlNode NodeKoment3 = Comment.CreateNode(XmlNodeType.Element, "text", "");
                        xmlAdd_text(NodeKoment3, TextBox__komentari.Text);
                        newNode.AppendChild(NodeKoment3);
                        // ieraksta <raksts> <komentari>
                        RakstsNode.AppendChild(newNode);
                        // insert <RakstuKomentari> <Raksts ID="x">
                        RakstuKomentari.InsertAfter(RakstsNode, RakstuKomentari.ChildNodes[RakstuKomentari.ChildNodes.Count - 1]);
                    }

                    Comment.Save(virtualPathDir + XMLfaili[SadalasIDx]);
                    Response.Redirect("DefaultZoom.aspx?value=" + String.Format(Request.QueryString["value"]));
                }
            }
        }
      }

    void xmlAdd_text(XmlNode newsNode, string texts)
    {
        try
        {
            newsNode.InnerXml = texts;
        }
        catch (XmlException ex)
        {
            string[] TagfreeTxt = texts.Split('<', '>');
            string apvieno = "";
            foreach (string txtGabali in TagfreeTxt)
            {
                apvieno += txtGabali;
            }
            newsNode.InnerXml = apvieno;
        }
    }
    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        LinkButton Lbb = (LinkButton)e.CommandSource;
        string LinkButtonName = Lbb.Text;//ToString();
        int NR = e.Item.ItemIndex;

        if (LinkButtonName == "Delet")
        {
            DispeyDa = DisplayTa.GetDataByRakstID(rakstaID_nr);
            SadalasIDx = DispeyDa[0].SadalasID - 1;
            RakstaID = RakstiDa[RowNr].ID_name;
            string virtualPathDir = Server.MapPath("~/");
            // Ielādē pareizo XML failu (katrai Sadaļai savs XML fails kas atrodās XMLfaili[] string arrayā.
            XmlTextReader Sadalla = new XmlTextReader(virtualPathDir + XMLfaili[DispeyDa[0].SadalasID - 1]);
            XmlDocument Comment = new XmlDocument();
            Comment.Load(Sadalla);
            Sadalla.Close();
            XmlNode RakstuKomentari = Comment.ChildNodes[2];
            //  int RakstuKom_Count = RakstuKomentari.ChildNodes.Count;
            foreach (XmlNode xmlRaksts in RakstuKomentari.ChildNodes)
            {
                if ((Convert.ToInt32(xmlRaksts.Attributes["ID"].Value)) == rakstaID_nr)
                {
                    if (xmlRaksts.ChildNodes.Count > 0)
                    {// Ja ir kaut 1 komentārs tad nolasa komentārus: 
                        int Ci = 0;
                        XmlNode delChild = xmlRaksts.ChildNodes[NR];
                        xmlRaksts.RemoveChild(delChild);
                        break;
                    }
                }
            }
            Comment.Save(virtualPathDir + XMLfaili[DispeyDa[0].SadalasID - 1]);
        }
    }
    protected void TextBox_Koment_Vards_TextChanged(object sender, EventArgs e)
    {
        // kods kas atrod Komentētāja IP adresi! 
        string ip;
        ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (!string.IsNullOrEmpty(ip))
        {
            string[] ipRange = ip.Split(',');
            int le = ipRange.Length - 1;
            string trueIP = ipRange[le];
        }
        else
        {
            ip = Request.ServerVariables["REMOTE_ADDR"];
        }
        // kautkādu IP es dabūnu.
        Label7.Text += ip;
    }


    DataTable CreateDataTableVideo(DataTable dataTable_video, string FileName, bool NEWprece)
    {
        // Make dataTable kollonas:

        DataColumn dc = new DataColumn();
        dc.DataType = Type.GetType("System.String");
        dc.ColumnName = "BildeLink"; // Pievieno Collonas Vardu
        dataTable_video.Columns.Add(dc);
        DataColumn dc2 = new DataColumn();
        dc2.DataType = Type.GetType("System.String");
        dc2.ColumnName = "FullLink";
        dataTable_video.Columns.Add(dc2);
        DataColumn dc3 = new DataColumn();
        dc3.DataType = Type.GetType("System.String");
        dc3.ColumnName = "AkcijCena";
        dataTable_video.Columns.Add(dc3);

        XmlTextReader menuXml = new XmlTextReader(FileName);
        XmlDocument MenuX = new XmlDocument();
        MenuX.Load(menuXml);
        menuXml.Close();

        //MenuX.Load(Server.MapPath("~/XmlAkcijaNEW.xml"));

        XmlNode MenuBegin = MenuX.ChildNodes[2];
        foreach (XmlNode xmlM in MenuBegin.ChildNodes)
        {
            if (NEWprece == false)
            {
                if (xmlM.Attributes["vards"].Value == "Akcija")
                {
                    foreach (XmlNode ahx in xmlM)
                    {
                        DataRow row = dataTable_video.NewRow();
                        row[0] = ahx.ChildNodes[0].InnerText;
                        row[1] = ahx.ChildNodes[1].InnerText;
                        row[2] = ahx.ChildNodes[2].InnerText;
                        dataTable_video.Rows.Add(row);
                    }
                }
            }
            else
            {
                if (xmlM.Attributes["vards"].Value == "NEWprece")
                {
                    foreach (XmlNode ahx in xmlM)
                    {
                        DataRow row = dataTable_video.NewRow();
                        row[0] = ReshapeBildeLink(ahx.ChildNodes[0].InnerText);
                        row[1] = ReshapeLink(ahx.ChildNodes[1].InnerText);
                        row[2] = ahx.ChildNodes[2].InnerText;
                        dataTable_video.Rows.Add(row);
                    }
                }
            }
        }

        return dataTable_video;
    }

    string ReshapeBildeLink(string Link)
    {
        string OK = "";
        OK = Link.Insert(9, "http://shop.parbmx.com/");
        OK = OK.Insert(OK.IndexOf("src=") + 5, "http://shop.parbmx.com/");

        return OK;
    }
    string ReshapeLink(string Link)
    {
        string OK = "";
        OK = Link.Insert(9, "http://shop.parbmx.com/");
        return OK;
    }
    //void AddMetaTags(string[] content, string[] Property, ControlCollection Mtags)
    //{
    //    for (int i = 0; i < content.Length; i++)
    //    {
    //        HtmlMeta theMetaTag1 = new HtmlMeta();
    //        theMetaTag1.ID = i.ToString();
    //        theMetaTag1.Attributes.Add("property", Property[i]);
    //        theMetaTag1.Attributes.Add("content", content[i]);
    //        Mtags.Add(theMetaTag1);
    //    }
    //}

}

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HiddenField hidDate = (HiddenField)FormView1.FindControl("hidTimeDate");
hidDate.Value = DateTime.Now.ToString();
}
}
VB.NET
Partial Public Class _Default
Inherits System.Web.UI.Page
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim hidDate As HiddenField = CType(FormView1.FindControl("hidTimeDate"), HiddenField)
hidDate.Value = DateTime.Now.ToString()
End Sub
End Class
 
